﻿using Common.Exceptions;
using Common.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Data.Entity;
using Wallpaper.Data.IDal;
using Wallpaper.Models.DTOs.Requests.User;
using Wallpaper.Models.DTOs.Responses.User;
using Wallpaper.Models.Entities;
using Wallpaper.Services.IService;

namespace Wallpaper.Services.Service
{
    public class UserService : IUserService
    {
        readonly IUserDal _userDal;
        readonly ILogger<UserService> _logger;

        public UserService(IUserDal userDal, ILogger<UserService> logger)
        {
            _userDal = userDal;
            _logger = logger;
        }

        /// <summary>
        /// 用户签到
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task CheckinAsync(string userId)
        {

            var result = await _userDal.GetDbSet<User>()
            .Where(u => u.Id == userId)
            .ExecuteUpdateAsync(setters => setters
                .SetProperty(u => u.Points, u => u.Points + 3)
                .SetProperty(u => u.UpdatedAt, DateTime.Now)
            );
            if (result == 0)
            {
                throw new BusinessException("该用户数据不存在或服务器错误", 404);
            }

        
        }

        public  async Task<bool> DeleteAsync(string id)
        {
            // 1. 参数验证
            if (string.IsNullOrWhiteSpace(id))
                throw new ArgumentException("角色ID不能为空", nameof(id));

            // 2. 检查角色是否存在
            var existingRole = await _userDal.GetByIdAsync(id);

            if (existingRole == null || existingRole.IsDeleted)
                throw new BusinessException("用户不存在或已被删除", 404);

            // 3. 执行删除
            return await _userDal.DeleteEntityAsync(existingRole);
        }

        public async Task<UserAppLoginResponse> GetByIdAsync(string userId)
        {
            User user = await _userDal.GetByIdAsync(userId);
            if (user == null)
                throw new  Exception("用户不存在");

            return new UserAppLoginResponse
            {
                Nickname = user.Nickname,
                AvatarUrl = user.AvatarUrl,
                Gender = user.Gender,
                Signature = user.Signature,
            };
        }


        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="queryRequest"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="queryRequest"></param>
        /// <returns></returns>
        public async Task<PagedResult<UserManagementResponse>> PageAsync(UserQueryRequest queryRequest)
        {
            var query = _userDal.GetQueryable();

            // 调试1：查看基础查询的SQL
            Console.WriteLine("=== 基础查询SQL ===");
            var baseSql = query.ToQueryString();
            Console.WriteLine(baseSql);
            // 关键词搜索（搜索昵称或签名）
            if (!string.IsNullOrWhiteSpace(queryRequest.Keyword))
            {
                query = query.Where(u => u.Nickname.Contains(queryRequest.Keyword)
                                      || u.Signature.Contains(queryRequest.Keyword));
            }

            // 昵称筛选
            if (!string.IsNullOrWhiteSpace(queryRequest.Nickname))
            {
                query = query.Where(u => u.Nickname.Contains(queryRequest.Nickname));
            }

            // 性别筛选
            if (!string.IsNullOrWhiteSpace(queryRequest.Gender))
            {
                query = query.Where(u => u.Gender == queryRequest.Gender);
            }

            // 状态筛选
            if (queryRequest.IsEnabled.HasValue)
            {
                query = query.Where(u => u.IsEnabled == queryRequest.IsEnabled.Value);
            }

            // 创建时间范围筛选
            if (queryRequest.StartTime.HasValue)
            {
                query = query.Where(u => u.CreatedAt >= queryRequest.StartTime.Value);
            }

            if (queryRequest.EndTime.HasValue)
            {
                query = query.Where(u => u.CreatedAt <= queryRequest.EndTime.Value);
            }

            // 排序（按创建时间降序）
            query = query.OrderByDescending(u => u.CreatedAt);

            // 获取总数
            var totalCount = await query.CountAsync();

            // 分页
            var items = await query
                .Skip((queryRequest.Page - 1) * queryRequest.PageSize)
                .Take(queryRequest.PageSize)
                .Select(u => new UserManagementResponse
                {
                    Id = u.Id,
                    Nickname = u.Nickname,
                    AvatarUrl = u.AvatarUrl,
                    Gender = u.Gender,
                    Points = u.Points,
                    TodayFreeDownloadCount = u.TodayFreeDownloadCount,
                    LastLoginTime = u.LastLoginTime,
                    CreatedTime = u.CreatedAt,
                    IsEnabled = u.IsEnabled,
                    Signature=u.Signature
                })
                .ToListAsync();

            return new PagedResult<UserManagementResponse>
            {
                Page = queryRequest.Page,
                PageSize = queryRequest.PageSize,
                TotalCount = totalCount,
                Items = items
            };
        }



        public async Task<bool> UpdateAsync(UpdateUserRequest request, string userId)
        {
            // 1. 参数验证
            if (request == null)
                throw new ArgumentNullException(nameof(request));

            if (string.IsNullOrEmpty(userId))
                throw new ArgumentException("用户ID不能为空", nameof(userId));

            try
            {
                // 2. 根据用户ID获取用户实体
                var user = await _userDal.GetByIdAsync(userId);
                if (user == null)
                {
                    throw new BusinessException($"用户 {userId} 不存在",404); // 使用自定义异常
                }

                // 3. 只更新提供了值的字段（部分更新）
                if (!string.IsNullOrEmpty(request.Nickname))
                    user.Nickname = request.Nickname.Trim();

                if (!string.IsNullOrEmpty(request.AvatarUrl))
                    user.AvatarUrl = request.AvatarUrl;

                if (!string.IsNullOrEmpty(request.Gender))
                    user.Gender = request.Gender;

                if (!string.IsNullOrEmpty(request.Signature))
                    user.Signature = request.Signature.Trim();

                // 4. 更新修改时间
                user.UpdatedAt = DateTime.Now;

                // 5. 保存到数据库
                return await _userDal.UpdateEntityAsync(user);
            }
            catch (Exception ex)
            {
                // 记录日志
                _logger.LogError(ex, "更新用户信息失败，用户ID: {UserId}", userId);
                throw new Exception("更新用户信息失败", ex); 
            }
        }

    }
}
